﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GlassStore.Models;
using System.IO;
using GlassStore.Helpers;
using GlassStore.ViewModels;

namespace GlassStore.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class CatalogueManagerController : Controller
    {
      GlassStoreEntities storeDB = new GlassStoreEntities();

        //
        // GET: /CatalogueManager/

        public ActionResult Index()
        {
          var topCatalogues = storeDB.TopCatalogues.ToList();
          return View(topCatalogues);
        }

        //
        // GET: /CatalogueManager/Details/5

        public ActionResult SubCatalogue(int topId)
        {
          var topCatalogue = storeDB.TopCatalogues.Include("SubCatalogues").Single(t => t.TopCatalogueId == topId);

          var subCatalogueBrowseViewModel = new SubCatalogueBrowseViewModel
          {
            TopCatalogue = topCatalogue,
            SubCatalogues = topCatalogue.SubCatalogues.ToList(),
          };

          return View(subCatalogueBrowseViewModel);
        }

        #region TopCatalogue

        //
        // GET: /CatalogueManager/CreateTop

        public ActionResult CreateTop()
        {
          var topCatalogue = new TopCatalogue();
          return View(topCatalogue);
        } 

        //
        // POST: /CatalogueManager/CreateTop

        [HttpPost]
        public ActionResult CreateTop(TopCatalogue topCatalogue)
        {
          if (ModelState.IsValid)
          {
            topCatalogue.PictureURL = HandleUpload(CatalogueLevel.Top);

            storeDB.AddToTopCatalogues(topCatalogue);
            storeDB.SaveChanges();

            return RedirectToAction("Index");
          }
          else
          {
            return View(topCatalogue);
          }
        }

        private string HandleUpload(CatalogueLevel level)
        {
          string url = string.Empty;
          if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
          {
            string path = string.Format("{0}uploads/{1}/", AppDomain.CurrentDomain.BaseDirectory, level.ToString());
            if (!Directory.Exists(path))
              Directory.CreateDirectory(path);

            string fileName = FileUploadHelpers.GenerateFileName() + Path.GetExtension(Request.Files[0].FileName);
            Request.Files[0].SaveAs(Path.Combine(path, fileName));

            url = string.Format("/uploads/{0}/{1}", level.ToString(), fileName);
          }
          return url;
        }
        
        //
        // GET: /CatalogueManager/EditTop/5

        public ActionResult EditTop(int id)
        {
          var topCatalogue = storeDB.TopCatalogues.Single(t => t.TopCatalogueId == id);
          return View(topCatalogue);
        }

        //
        // POST: /CatalogueManager/EditTop/5

        [HttpPost]
        public ActionResult EditTop(int id, FormCollection collection)
        {
          var topCatalogue = storeDB.TopCatalogues.Single(t => t.TopCatalogueId == id);
            try
            {
              UpdateModel(topCatalogue);

              string url = HandleUpload(CatalogueLevel.Top);
              if (!string.IsNullOrEmpty(url))
                topCatalogue.PictureURL = url;

              storeDB.SaveChanges();
 
                return RedirectToAction("Index");
            }
            catch
            {
              return View(topCatalogue);
            }
        }

        //
        // GET: /CatalogueManager/DeleteTop/5
 
        public ActionResult DeleteTop(int id)
        {
          var topCatalogue = storeDB.TopCatalogues.Single(t => t.TopCatalogueId == id);
          return View(topCatalogue);
        }

        //
        // POST: /CatalogueManager/DeleteTop/5

        [HttpPost]
        public ActionResult DeleteTop(int id, FormCollection collection)
        {
          try
          {
              var topCatalogue = storeDB.TopCatalogues.Include("SubCatalogues").Include("SubCatalogues.GlassCatalogues").Single(t => t.TopCatalogueId == id);
            if (!string.IsNullOrEmpty(topCatalogue.PictureURL))
            {
              string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, topCatalogue.PictureURL.Remove(0,1));
              try
              {
                System.IO.File.Delete(fileName);
              }
              catch
              {
              }
            }
            storeDB.DeleteObject(topCatalogue);
            storeDB.SaveChanges();

            return View("DeletedTop");
          }
          catch
          {
          }
          var topCatalogues = storeDB.TopCatalogues.ToList();
          return View(topCatalogues);
        }

        #endregion

        #region SubCatalogue

        //
        // GET: /CatalogueManager/CreateSub?topId=1

        public ActionResult CreateSub(int topId)
        {
          var subCatalogueViewModel = new SubCatalogueViewModel
          {
            SubCatalogue = new SubCatalogue { TopCatalogueId = topId},
            TopCatalogue = storeDB.TopCatalogues.Single(t => t.TopCatalogueId == topId),
          };
          return View(subCatalogueViewModel);
        }

        //
        // POST: /CatalogueManager/CreateSub

        [HttpPost]
        public ActionResult CreateSub(SubCatalogue subCatalogue)
        {
          if (ModelState.IsValid)
          {
            subCatalogue.PictureURL = HandleUpload(CatalogueLevel.Sub);

            storeDB.AddToSubCatalogues(subCatalogue);
            storeDB.SaveChanges();

            return RedirectToAction("SubCatalogue", new { topid = subCatalogue.TopCatalogueId });
          }
          else
          {
            return View(subCatalogue);
          }
        }

        //
        // GET: /CatalogueManager/EditSub/5

        public ActionResult EditSub(int id)
        {
          var subCatalogue = storeDB.SubCatalogues.Include("TopCatalogue").Single(t => t.SubCatalogueId == id);
          var subCatalogueViewModel = new SubCatalogueViewModel
          {
            SubCatalogue = subCatalogue,
            TopCatalogue = subCatalogue.TopCatalogue,
          };
          return View(subCatalogueViewModel);
        }

        //
        // POST: /CatalogueManager/EditSub/5

        [HttpPost]
        public ActionResult EditSub(int id, FormCollection collection)
        {
          var subCatalogue = storeDB.SubCatalogues.Include("TopCatalogue").Single(t => t.SubCatalogueId == id);
          try
          {
            UpdateModel(subCatalogue, "SubCatalogue");

            string url = HandleUpload(CatalogueLevel.Sub);
            if (!string.IsNullOrEmpty(url))
              subCatalogue.PictureURL = url;

            storeDB.SaveChanges();

            return RedirectToAction("SubCatalogue", new { topId = subCatalogue.TopCatalogueId});
          }
          catch
          {
            var subCatalogueViewModel = new SubCatalogueViewModel
            {
              SubCatalogue = subCatalogue,
              TopCatalogue = subCatalogue.TopCatalogue,
            };
            return View(subCatalogueViewModel);
          }
        }

        //
        // GET: /CatalogueManager/DeleteSub/5

        public ActionResult DeleteSub(int id)
        {
          var subCatalogue = storeDB.SubCatalogues.Include("TopCatalogue").Single(t => t.SubCatalogueId == id);
          var subCatalogueViewModel = new SubCatalogueViewModel
          {
            SubCatalogue = subCatalogue,
            TopCatalogue = subCatalogue.TopCatalogue,
          };
          return View(subCatalogueViewModel);
        }

        //
        // POST: /CatalogueManager/DeleteSub/5

        [HttpPost]
        public ActionResult DeleteSub(int id, FormCollection collection)
        {
          try
          {
            var subCatalogue = storeDB.SubCatalogues.Single(t => t.SubCatalogueId == id);
            if (!string.IsNullOrEmpty(subCatalogue.PictureURL))
            {
              string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, subCatalogue.PictureURL.Remove(0, 1));
              try
              {
                System.IO.File.Delete(fileName);
              }
              catch
              {
              }
            }
            storeDB.DeleteObject(subCatalogue);
            storeDB.SaveChanges();

            return View("DeletedSub", subCatalogue.TopCatalogueId);
          }
          catch
          {
            return View("Index");
          }
        }

        #endregion
    }

  public enum CatalogueLevel
  {
    Top,
    Sub
  }
}
